/* Copyright (c) Koninklijke Philips Electronics NV 2013
 * All rights are reserved. Reproduction or dissemination 
 * in whole or in part is prohibited without the prior written 
 * consent of the copyright holder.
 *
 * Under no circumstances is this software to be combined with any   
 * open source software in any way or licensed under any open source 
 * license without the express written permission of Koninklijke 
 * Philips Electronics N.V. "Open source software" means any software 
 * under an open source license; an "open source license" is any 
 * license certified by the Open Source Initiative.
 *                
 * Philips Research Laboratories
 * Eindhoven, The Netherlands
 *
 */
package com.philips.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.json.JSONException;
import org.json.JSONObject;

import com.philips.research.vp.utilities.UtilsVP;
import com.philips.util.Common;

/**
 * Extracts air quality and weather data from json files
 * retrieved from the ixuanWu.com.cn website.
 * @author fu.yuan 310124879
 */
public class AirService {
	private static String jsonPath=Common.realPath+"data/json/";
	private static String excelPath=Common.realPath+"data/excel/";
	private static String tempFilePath=Common.realPath+"data/template/shanghai_air_temp.xls";
	private static String nowdt;
	private static String nowtime;
	private static String nowdate;
	private static String errorMsg="success";
	/**
	 * 
	 * @param airjson : air json format data
	 * @param citykey : city key
	 * @return
	 */
	public String saveAir(String airjson,String citykey){
		this.nowdt=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(System.currentTimeMillis());
		this.nowtime=new SimpleDateFormat("yyyyMMddhhmmss").format(System.currentTimeMillis());
		this.nowdate=new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
		HSSFWorkbook wb=null;
		try {
				File excelfile=new File(excelPath+citykey+nowdate+".xls");
				if(!excelfile.isFile()){
				    wb=new HSSFWorkbook(new FileInputStream(new File(tempFilePath)));
				}else{
					wb=new HSSFWorkbook(new FileInputStream(excelfile));
				}
				JSONObject jso = new JSONObject(airjson);
				JSONObject cities = (JSONObject) jso.get("cities");
				for (String city : JSONObject.getNames(cities)) {
					JSONObject cityData = (JSONObject) cities.get(city);
					String cityDatakey=cityData.getString("key");
					if(cityDatakey.equals(citykey)){
						
						PrintWriter out = UtilsVP.openWriteFile(jsonPath+citykey+nowtime+".txt");
						UtilsVP.writeln(out, cityData.toString());
						UtilsVP.close(out);
						
						if (cityData.has("weather_ex")) {
							HSSFSheet weatherSheet=wb.getSheet("天气");
							String rec=weatherSheet.getRow(0).getCell(12).toString().trim();
							int record=Integer.parseInt(rec.substring(rec.indexOf(":")+1));
							int line=record+2;
							HSSFRow weatherRow=weatherSheet.getRow(line);
							JSONObject weatherEx = (JSONObject) cityData.get("weather_ex");
							weatherRow.getCell(0).setCellValue(nowdt);
							weatherRow.getCell(1).setCellValue(cityData.get("lon").toString());
							weatherRow.getCell(2).setCellValue(cityData.get("lat").toString());
							weatherRow.getCell(3).setCellValue(getValue(weatherEx,"wind_degrees"));
							if (cityData.has("gov")) {
								JSONObject gov = (JSONObject) cityData.get("gov");
								weatherRow.getCell(4).setCellValue(getValue(gov, "t"));
							} else {
								weatherRow.getCell(4).setCellValue("NaN");
							}
							weatherRow.getCell(5).setCellValue(getValue(weatherEx,"wind_kph"));
							weatherRow.getCell(6).setCellValue(getValue(weatherEx,"temp_c"));
							weatherRow.getCell(7).setCellValue(getValue(weatherEx,"high"));
							weatherRow.getCell(8).setCellValue(getValue(weatherEx,"weather"));
							weatherRow.getCell(9).setCellValue(getValue(weatherEx,"low"));
							weatherRow.getCell(10).setCellValue(getValue(weatherEx,"icon"));
							weatherRow.getCell(11).setCellValue(cityData.get("weather").toString());
							weatherSheet.getRow(0).getCell(12).setCellValue("record:"+(record+1));
						}if (cityData.has("gov")) {
							JSONObject gov = (JSONObject) cityData.get("gov");
							if (gov.has("stations")) {
								JSONObject stations = (JSONObject) gov.get("stations");
								for (int i = 0; i < JSONObject.getNames(stations).length; i++) {
									String station= JSONObject.getNames(stations)[i];
									JSONObject stationData = (JSONObject) stations.get(station);
									HSSFSheet govsheet=wb.getSheet(station);
									String rec=govsheet.getRow(0).getCell(11).toString().trim();
									int record=Integer.parseInt(rec.substring(rec.indexOf(":")+1));
									int line=record+2;
									HSSFRow govRow=govsheet.getRow(line);
									govRow.getCell(0).setCellValue(nowdt);
									govRow.getCell(1).setCellValue(getValue(stationData, "lon"));
									govRow.getCell(2).setCellValue(getValue(stationData, "lat"));
									govRow.getCell(3).setCellValue(getValue(stationData, "t"));
									govRow.getCell(4).setCellValue(getValue(stationData, "idx"));
									govRow.getCell(5).setCellValue(getValue(stationData, "pm25"));
									govRow.getCell(6).setCellValue(getValue(stationData, "pm10"));
									govRow.getCell(7).setCellValue(getValue(stationData, "no2"));
									govRow.getCell(8).setCellValue(getValue(stationData, "so2"));
									govRow.getCell(9).setCellValue(getValue(stationData, "o3"));
									govRow.getCell(10).setCellValue(getValue(stationData, "co"));
									govsheet.getRow(0).getCell(11).setCellValue("record:"+(record+1));
									
								}
							}
						}
					}
				}
				OutputStream excelgovout = new FileOutputStream(excelPath+citykey+nowdate+".xls");
		        wb.write(excelgovout);
			} catch (Exception e) {
				errorMsg=e.getMessage();
			}
	return errorMsg;
	}

	private static String getValue(JSONObject jso, String key) {
		if (jso.has(key)) {
			try {
				return jso.get(key).toString();
			} catch (JSONException e) {
				e.printStackTrace();
				return "NaN";
			}
		} 
		return "NaN";
	}
	
	public static String readFile(String filename) {
		BufferedReader in = UtilsVP.openReadFile(filename);
		String line;
		StringBuilder sb = new StringBuilder();
		
		while ((line = UtilsVP.readln(in)) != null) {
			if (UtilsVP.notEmptyAndNoComment(line)) {
				sb.append(line);
			}
		}
		return sb.toString();
	}
	public static void main(String[] args) {
		try {
		AirService as=new AirService();
			String airjson=readFile("c:/temp/data.txt");
			as.saveAir(airjson,"shanghai");
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
	
}
class A{
	public Date start;
	public Date end;
}


